// 权限管理工具类

const ADMIN_CREDENTIALS = {
  username: 'admin',
  password: '123456',
};

const STORAGE_KEYS = {
  IS_ADMIN: 'env_manager_is_admin',
  LOGIN_CLICK_COUNT: 'env_manager_login_click_count',
};

export class AuthManager {
  private static instance: AuthManager;
  private isAdmin: boolean = false;
  private loginClickCount: number = 0;

  private constructor() {
    this.loadFromStorage();
  }

  public static getInstance(): AuthManager {
    if (!AuthManager.instance) {
      AuthManager.instance = new AuthManager();
    }
    return AuthManager.instance;
  }

  // 从localStorage加载状态
  private loadFromStorage(): void {
    const isAdmin = localStorage.getItem(STORAGE_KEYS.IS_ADMIN);
    const clickCount = localStorage.getItem(STORAGE_KEYS.LOGIN_CLICK_COUNT);
    
    this.isAdmin = isAdmin === 'true';
    this.loginClickCount = clickCount ? parseInt(clickCount, 10) : 0;
  }

  // 保存状态到localStorage
  private saveToStorage(): void {
    localStorage.setItem(STORAGE_KEYS.IS_ADMIN, this.isAdmin.toString());
    localStorage.setItem(STORAGE_KEYS.LOGIN_CLICK_COUNT, this.loginClickCount.toString());
  }

  // 获取管理员状态
  public getIsAdmin(): boolean {
    return this.isAdmin;
  }

  // 获取点击次数
  public getLoginClickCount(): number {
    return this.loginClickCount;
  }

  // Logo点击处理
  public handleLogoClick(): boolean {
    this.loginClickCount++;
    this.saveToStorage();
    
    // 如果点击5次，显示登录框
    if (this.loginClickCount >= 5) {
      this.resetClickCount();
      return true;
    }
    
    return false;
  }

  // 重置点击次数
  public resetClickCount(): void {
    this.loginClickCount = 0;
    this.saveToStorage();
  }

  // 管理员登录
  public login(username: string, password: string): boolean {
    if (username === ADMIN_CREDENTIALS.username && password === ADMIN_CREDENTIALS.password) {
      this.isAdmin = true;
      this.saveToStorage();
      return true;
    }
    return false;
  }

  // 管理员退出登录
  public logout(): void {
    this.isAdmin = false;
    this.saveToStorage();
  }

  // 清除所有数据
  public clearAll(): void {
    this.isAdmin = false;
    this.loginClickCount = 0;
    localStorage.removeItem(STORAGE_KEYS.IS_ADMIN);
    localStorage.removeItem(STORAGE_KEYS.LOGIN_CLICK_COUNT);
  }
}

// 导出单例实例
export const authManager = AuthManager.getInstance();
